package aaaBlogger.recy;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.CloseWindowListener;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.browser.VisibilityWindowListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import aaBaolilo.CallJava;

import com.attilax.Closure;
import com.attilax.io.filex;

public class atiBrowserExample {
	int index;
	boolean busy;
	boolean busy2=true;
	// Image images[];
	// Text location;
	public Browser browser;
//	static final String[] imageLocations = { "eclipse01.bmp", "eclipse02.bmp",
//			"eclipse03.bmp", "eclipse04.bmp", "eclipse05.bmp", "eclipse06.bmp",
//			"eclipse07.bmp", "eclipse08.bmp", "eclipse09.bmp", "eclipse10.bmp",
//			"eclipse11.bmp", "eclipse12.bmp", };
	//static final String iconLocation = "document.gif";
	public String urlgoto ;//"http://www.baidu.com";;

	public atiBrowserExample(Composite parent) {
		// javafx.scene.web.WebView;

		final Display display = parent.getDisplay();
		FormLayout layout = new FormLayout();
		parent.setLayout(layout);

		// location = new Text(parent, SWT.BORDER);
		// images = new Image[] { new Image(display, "C:/icons/web/go.gif") };
		final Canvas canvas = new Canvas(parent, SWT.NO_BACKGROUND);
		// final Rectangle rect = images[0].getBounds();
		canvas.addListener(SWT.Paint, new Listener() {
			public void handleEvent(Event e) {
				Point pt = canvas.getSize();
				// e.gc.drawImage(images[index], 0, 0, rect.width, rect.height,
				// 0,
				// 0, pt.x, pt.y);
			}
		});
		canvas.addListener(SWT.MouseDown, new Listener() {
			public void handleEvent(Event e) {
				browser.setUrl(getResourceString("Startup"));
			}
		});

		// display.asyncExec(new Runnable() {
		// public void run() {
		// if (canvas.isDisposed())
		// return;
		// if (busy) {
		// index++;
		// if (index == images.length)
		// index = 0;
		// canvas.redraw();
		// }
		// display.timerExec(150, this);
		// }
		// });
		final Label status = new Label(parent, SWT.NONE);
		final ProgressBar progressBar = new ProgressBar(parent, SWT.NONE);
		FormData data = new FormData();
		data.top = new FormAttachment(0, 5);
		// toolbar.setLayoutData(data);
		data = new FormData();
		data.left = new FormAttachment(0, 0);
		data.right = new FormAttachment(100, 0);
		data.top = new FormAttachment(canvas, 5, SWT.DEFAULT);
		data.bottom = new FormAttachment(status, -5, SWT.DEFAULT);
		try {
			browser = new Browser(parent, SWT.NONE);
			browser.setLayoutData(data);
		} catch (SWTError e) {
			Label label = new Label(parent, SWT.CENTER | SWT.WRAP);
			label.setText(getResourceString("BrowserNotCreated"));
			label.setLayoutData(data);
		}
		data = new FormData();
		data.width = 1;
		data.height = 1;
		data.top = new FormAttachment(0, 5);
		data.right = new FormAttachment(100, -5);
 		canvas.setLayoutData(data);
		data = new FormData();
		canvas.setVisible(false);
		// data.top = new FormAttachment(toolbar, 0, SWT.TOP);
		// data.left = new FormAttachment(toolbar, 5, SWT.RIGHT);
		data.right = new FormAttachment(canvas, -5, SWT.DEFAULT);
		// location.setLayoutData(data);
		data = new FormData();
		data.left = new FormAttachment(0, 5);
		data.right = new FormAttachment(progressBar, 0, SWT.DEFAULT);
		data.bottom = new FormAttachment(100, -5);
		status.setLayoutData(data);

		data = new FormData();
		data.right = new FormAttachment(100, -5);
		data.bottom = new FormAttachment(100, -5);
		progressBar.setLayoutData(data);
		if (browser != null) {
			// itemBack.setEnabled(browser.isBackEnabled());
			// itemForward.setEnabled(browser.isForwardEnabled());

			Listener listener = new Listener() {
				public void handleEvent(Event event) {
					// ToolItem item = (ToolItem) event.widget;
					// if (item == itemBack)
					// browser.back();
					// else if (item == itemForward)
					// browser.forward();
					// else if (item == itemStop)
					// browser.stop();
					// else if (item == itemRefresh)
					// browser.refresh();
					// else if (item == itemGo)
					// browser.setUrl(location.getText());
				}
			};
			browser.addLocationListener(new LocationListener() {
				public void changed(LocationEvent event) {
					busy = true;
					// if (event.top)
					// location.setText(event.location);
				}

				public void changing(LocationEvent event) {
				}
			});
			// browser.addProgressListener(new ProgressListener() {
			// // public void changed(ProgressEvent event) {
			// // if (event.total == 0)
			// // return;
			// // int ratio = event.current * 100 / event.total;
			// // progressBar.setSelection(ratio);
			// // busy = event.current != event.total;
			// // if (!busy) {
			// // index = 0;
			// // canvas.redraw();
			// // }
			// // }
			// //
			// /**
			// * attilax
			// */
			// public void completed(ProgressEvent event) {
			// // itemBack.setEnabled(browser.isBackEnabled());
			// // itemForward.setEnabled(browser.isForwardEnabled());
			// progressBar.setSelection(0);
			// busy = false;
			// index = 0;
			// System.out.println("---kwww");
			// //kw
			// String string = "document.getElementById('kw').value='aaaa'";
			// browser.execute(string);
			// canvas.redraw();
			// }
			// });
			browser.addStatusTextListener(new StatusTextListener() {
				public void changed(StatusTextEvent event) {
					status.setText(event.text);
				}
			});
			if (parent instanceof Shell) {
				final Shell shell = (Shell) parent;
				browser.addTitleListener(new TitleListener() {
					public void changed(TitleEvent event) {
						shell.setText(event.title + " - "
								+ getResourceString("window.title"));
					}
				});
			}
			// itemBack.addListener(SWT.Selection, listener);
			// itemForward.addListener(SWT.Selection, listener);
			// itemStop.addListener(SWT.Selection, listener);
			// itemRefresh.addListener(SWT.Selection, listener);
			// itemGo.addListener(SWT.Selection, listener);
			// location.addListener(SWT.DefaultSelection, new Listener() {
			// public void handleEvent(Event e) {
			// browser.setUrl(location.getText());
			// }
			// });
			initialize(display, browser);

		regJscallback();
		}
	}

	private void regJscallback() {
		 
		new aaBaolilo.CallJavaPaa1(browser, "mycallJava");
		new aaBaolilo.CallJavaPaa1(browser, "sendNSCommand_json");
		new aaBaolilo.CallJavaPaa1(browser, "sendNSCommand");
		
	}

	static String getResourceString(String key) {
		try {
			return "key";
		} catch (MissingResourceException e) {
			return key;
		} catch (NullPointerException e) {
			return "!" + key + "!";
		}
	}

	static String getResourceString(String key, Object[] args) {
		try {
			return MessageFormat.format(getResourceString(key), args);
		} catch (MissingResourceException e) {
			return key;
		} catch (NullPointerException e) {
			return "!" + key + "!";
		}
	}

	/**
	 * \invoke by construtsc
	 * 
	 * @param display
	 * @param browser
	 */
	static void initialize(final Display display, Browser browser) {
		browser.addOpenWindowListener(new OpenWindowListener() {
			public void open(WindowEvent event) {
				System.out.println("Open");
				Shell shell = new Shell(display);
				shell.setLayout(new FillLayout());
				Browser browser = new Browser(shell, SWT.NONE);
				initialize(display, browser);
				event.browser = browser;
			//	regJscallback();
				new aaBaolilo.CallJavaPaa1(browser, "mycallJava");
				
			}
		});
		browser.addVisibilityWindowListener(new VisibilityWindowListener() {
			public void hide(WindowEvent event) {
			}

			public void show(WindowEvent event) {
				System.out.println("Show");
				Browser browser = (Browser) event.widget;
				Shell shell = browser.getShell();
				if (event.location != null)
					shell.setLocation(event.location);
				if (event.size != null) {
					Point size = event.size;
					shell.setSize(shell.computeSize(size.x, size.y));
				}
				shell.open();
			}
		});
		browser.addCloseWindowListener(new CloseWindowListener() {
			public void close(WindowEvent event) {
				System.out.println("Close");
				Browser browser = (Browser) event.widget;
				Shell shell = browser.getShell();
				shell.close();
			}
		});
	}

	public void dispose() {
		freeResources();
	}

	void freeResources() {
		// if (images != null) {
		// for (int i = 0; i < images.length; ++i) {
		// final Image image = images[i];
		// if (image != null)
		// image.dispose();
		// }
		// images = null;
		// }
	}

	public void setFocus() {
		// location.setFocus();
	}

	public static void main(String[] args) {

		Display display = new Display();
		Shell shell = new Shell(display);
		shell.setLayout(new FillLayout());
		shell.setText("Browser example");
		shell.setVisible(false);
		// shell.setSize(1, 1);

		atiBrowserExample atiBrowserExampleinstance = new atiBrowserExample(
				shell);
		// Image icon = new Image(display, "C:/icons/web/go.gif");
		// shell.setImage(icon);

		shell.open();
		shell.setVisible(false);
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		// icon.dispose();
		atiBrowserExampleinstance.dispose();
		display.dispose();
	}
	ProgressListener  prgrsLsnr;
	
	
	public void addProgressListener4exeJStxt(final String js_txt, final Closure closure) {
		
		prgrsLsnr=new ProgressListener() {
			//
			/**
			 * attilax
			 */
			public void completed(ProgressEvent event) {
				// itemBack.setEnabled(browser.isBackEnabled());
				// itemForward.setEnabled(browser.isForwardEnabled());
				// progressBar.setSelection(0);
				busy = false;
				index = 0;
				busy2=true;
				System.out.println("---page load completed event");
				// kw
				String string = js_txt;// filex.read(js_path);
				browser.execute(string);
				
			//	System.out.println(browser.execute("document.cookie"));
				
				if(prgrsLsnr!=null)
					browser.removeProgressListener(prgrsLsnr);
				
				busy2=false;
				try {
					closure.execute(null);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				System.out.println("---page load  completed event finish");
			//	System.out.println(browser.getText());
				// canvas.redraw();
			}

			@Override
			public void changed(ProgressEvent paramProgressEvent) {
				// TODO Auto-generated method stub

			}
		};
		browser.addProgressListener(prgrsLsnr);

	}
	public void addProgressListener(final String js_path, final Closure closure) {
	
		prgrsLsnr=new ProgressListener() {
			//
			/**
			 * attilax
			 */
			public void completed(ProgressEvent event) {
				// itemBack.setEnabled(browser.isBackEnabled());
				// itemForward.setEnabled(browser.isForwardEnabled());
				// progressBar.setSelection(0);
				busy = false;
				index = 0;
				busy2=true;
				System.out.println("---page load completed event");
				// kw
				String string =  filex.read(js_path);
				browser.execute(string);
				
			//	System.out.println(browser.execute("document.cookie"));
				
				if(prgrsLsnr!=null)
					browser.removeProgressListener(prgrsLsnr);
				
				busy2=false;
				try {
					closure.execute(null);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				System.out.println("---page load  completed event finish");
			//	System.out.println(browser.getText());
				// canvas.redraw();
			}

			@Override
			public void changed(ProgressEvent paramProgressEvent) {
				// TODO Auto-generated method stub

			}
		};
		browser.addProgressListener(prgrsLsnr);

	}
	
	
	public void addProgressListener_befDelLister(final String js_path, final Closure closure, final Closure closure2_change) {
		if(prgrsLsnr!=null)
			browser.removeProgressListener(prgrsLsnr);
		prgrsLsnr=new ProgressListener() {
			//
			/**
			 * attilax
			 */
			public void completed(ProgressEvent event) {
				// itemBack.setEnabled(browser.isBackEnabled());
				// itemForward.setEnabled(browser.isForwardEnabled());
				// progressBar.setSelection(0);
				busy = false;
				index = 0;
				busy2=true;
				System.out.println("---page load completed event");
				// kw
				String string =  filex.read(js_path);
				browser.execute(string);
				
			//	System.out.println(browser.execute("document.cookie"));
				
			
				
				busy2=false;
				try {
					closure.execute(null);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				System.out.println("---page load  completed event finish");
			//	System.out.println(browser.getText());
				// canvas.redraw();
			}

			@Override
			public void changed(ProgressEvent paramProgressEvent) {
//				System.out.println("---page changed   event  ");
//				try {
//					closure2_change.execute(null);
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				System.out.println("---page changed event finish");
			}
		};
		browser.addProgressListener(prgrsLsnr);

	}

	public void ini() {
		browser.setUrl(urlgoto);
		
	}

	public void gotoUrl(String urlgoto) {
	this.urlgoto=urlgoto;
	
		
	}
	public String getUrlgoto() {
		return urlgoto;
	}

	public void setUrlgoto(String urlgoto) {
		this.urlgoto = urlgoto;
	}

	public void gotoUrl( ) {
		browser.setUrl(this.urlgoto);
	
		
	}
	

	public void waitFinish(Display display) {
		while(busy2)
		{
			System.out.println("--waitFinish");
			try {
				Thread.sleep(500000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			//display.sleep();
		}
		
	}

	public void regJsCallbackMeth(String string, Closure closure) {
		CallJavaPaa1.eventMap.put(string, closure);
		
		
	}

	public boolean executeJs(String file) {
		String t=filex.read(file);
	return	browser.execute(t);
		
	}
	
	public boolean executeJsTxt(String txt) {
	 
	return	browser.execute(txt);
		
	}

	public void regJsCallbackMeth_4jsonParam(String string, Closure closure) {
		CallJavaPaa1.eventMap.put(string, closure);
		
	}
}